

package Server;

import CLIENT.Client;
import CLIENT.Message;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * This class listenes to new messages from connected users ( server side)
 * @author Yaniv Kalif
 */
public class ServerMessageListener implements Runnable
{
    Client _client;
    ObjectInputStream in = null;
    ServerMainChatPanel _CreatorP;
   /**
    * Constructor for ServerMessageListener
    * @param client
    * @param Creator - the creator panel
    * @throws IOException
    */
    public ServerMessageListener(Client client,ServerMainChatPanel Creator) throws IOException
    {
        _client = client;
        in = new ObjectInputStream(client.GetSocket().getInputStream());
        _CreatorP=Creator;
    }
    public void run()
    {
        try 
        {
            String msg = null;
            Message m = null;
            try {

                while ((m = (Message) in.readObject()) != null)
                {
                    if (in != null)
                    {
                        System.out.println("" + m.GetClientsrc() + ":" + m);
                        if (m.GetisSystemMessage())
                        {
                            _CreatorP.AddClientToUsersList(m.GetString());

                            // Update clients with users list
                            _CreatorP.UpdateClientsList();

                        }
                        else
                        {
                            _client.SetName(m.GetClientsrc());
                            try {
                                _CreatorP.SendMessage(_client, m.GetString(), m.GetClientdst()); // send the message to all the users
                            } catch (UnknownHostException ex) {
                                Logger.getLogger(ServerMessageListener.class.getName()).log(Level.SEVERE, null, ex);
                            } catch (InterruptedException ex) {
                                Logger.getLogger(ServerMessageListener.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                    }
                }
            }
            catch (ClassNotFoundException ex)
            {
                Logger.getLogger(ServerMessageListener.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        catch (IOException ex)
        {
            Logger.getLogger(ServerMessageListener.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}
